package com.rzjm.exercise.module.controller;

import cn.hutool.core.util.StrUtil;
import com.rzjm.exercise.common.base.controller.BaseController;
import com.rzjm.exercise.common.base.data.DataTableLayUI;
import com.rzjm.exercise.common.log.annotation.Log;
import com.rzjm.exercise.common.utils.*;
import com.rzjm.exercise.module.domain.*;
import com.rzjm.exercise.module.service.*;
import com.rzjm.exercise.sys.core.dict.annotation.DictBody;
import com.rzjm.exercise.sys.system.user.domain.UserDO;
import com.rzjm.exercise.sys.system.user.service.UserService;
import net.sf.json.JSONObject;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.*;

/**
 * 特殊岗位
 *
 * @author mr.zhou
 * @email zhouwei_nice@163.com
 * @date 2018-12-15 22:20:07
 */

@Controller
@RequestMapping("/module/shop/post")
public class ShopPostController extends BaseController {
    @Resource
    private ShopPostService shopPostService;
    @Resource
    private ShopPostRecordService shopPostRecordService;
    @Resource
    private UserService userService;
    @Resource
    private ShopService shopService;
    @Resource
    private WxTemplateService wxTemplateService;
    @Resource
    private UserMpService userMpService;
    @Resource
    private WxUserService wxUserService;

    @Value("${projecturl.imgurl}")
    private String imgurl;
    @Value("${projecturl.uploadPath}")
    private String uploadPath;

    @Value("${wechat.appid_mp}")
    private String appidMp;//公众号appid
    @Value("${wechat.secret_mp}")
    private String secretMp;//公众号secret

    @Log("查询特殊岗位页面")
    @GetMapping()
    @RequiresPermissions("module:shoppost:shoppost")
    String ShopPost() {
        return "module/shop/post/post";
    }

    @Log("查询特殊岗位页面")
    @GetMapping("/record")
    @RequiresPermissions("module:shoppost:record")
    String ShopPostRecord(Model model) {
        UserDO user = getUser();
        List<Shop> shops = new ArrayList<>();
        if(user.getUserType() == 0 || user.getUserType() == 1){//平台管理员可以查看所有的
            shops = shopService.selectAllList();
        } else if(user.getUserType() == 2 ){//集团管理员可以查看自己所管辖的
            Map<String,Object> map = new HashMap<>();
            map.put("jituan_user_id",user.getUserId());
            shops = shopService.getPageByUserId(map);
        } else if(user.getUserType() == 3){//片区管理员可以查看自己所管辖的
            Map<String,Object> map = new HashMap<>();
            map.put("sys_user_id",user.getUserId());
            shops = shopService.getPageByUserId(map);
        } else if(user.getUserType() == 4 || user.getUserType() == 5 || user.getUserType() == 6){//分厂和巡检人员只能查看自己绑定的那个一个
            Map<String,Object> map = new HashMap<>();
            map.put("id",user.getShopId());
            shops = shopService.getPageByUserId(map);
        }
        model.addAttribute("shops", shops);
        return "module/shop/post/record";
    }

    @Log("查询特殊岗位")
    @ResponseBody
    @DictBody
    @GetMapping("/list")
    @RequiresPermissions("module:shoppost:shoppost")
    public DataTableLayUI<ShopPost> list(DataTableLayUI<ShopPost> condition) {
//        UserDO user = getUser();
        DataTableLayUI<ShopPost> dt = shopPostService.pageSearchLayUI(condition);
        List<ShopPost> list = dt.getData();
        list.forEach(post->{
            if(StrUtil.isNotEmpty(post.getQrCode())){
                post.setQrCode(imgurl + post.getQrCode());
            }
        });
        return dt;
    }


    /**
     * 下载岗位二维码
     */
    @Log("下载岗位二维码")
    @GetMapping("/download/{postNum}")
    public void download(@PathVariable("postNum") String postNum, HttpServletResponse response) {
        ShopPost shopPost = shopPostService.selectByUniqueColumn("post_num",postNum);
        if(shopPost!=null){
            FileUtils.download(uploadPath + shopPost.getQrCode(),response);
        }
    }


    @Log("查询特殊岗位")
    @ResponseBody
    @DictBody
    @GetMapping("/record/list")
    @RequiresPermissions("module:shoppost:record")
    public DataTableLayUI<ShopPostRecord> recordList(DataTableLayUI<ShopPostRecord> condition) {
        UserDO user = getUser();
        DataTableLayUI<ShopPostRecord> dt = shopPostRecordService.pageSearchLayUI(condition);
        List<ShopPostRecord> list = dt.getData();
        list.forEach(record->{
            if(StrUtil.isNotEmpty(record.getFireImg())){
                String[] fires = record.getFireImg().split(",");
                List<String> fireList = new ArrayList<>();
                for (String img : fires){
                    fireList.add(imgurl + img);
                }
                record.setFireImgList(fireList);
            }
            if(StrUtil.isNotEmpty(record.getImgs())){
                String[] imgs = record.getImgs().split(",");
                List<String> imgList = new ArrayList<>();
                for (String img : imgs){
                    imgList.add(imgurl + img);
                }
                record.setImgList(imgList);
            }
        });
        return dt;
    }

    @Log("新增特殊岗位页面")
    @GetMapping("/add")
    @RequiresPermissions("module:shoppost:add")
    String add(Model model) {
        UserDO user = getUser();
        ShopPost shopPost = new ShopPost();
        List<Shop> shops = new ArrayList<>();
        if(user.getUserType() == 0 || user.getUserType() == 1){//平台管理员可以查看所有的
            shops = shopService.selectAllList();
        } else if(user.getUserType() == 2 ){//集团管理员可以查看自己所管辖的
            Map<String,Object> map = new HashMap<>();
            map.put("jituan_user_id",user.getUserId());
            shops = shopService.getPageByUserId(map);
        } else if(user.getUserType() == 3){//片区管理员可以查看自己所管辖的
            Map<String,Object> map = new HashMap<>();
            map.put("sys_user_id",user.getUserId());
            shops = shopService.getPageByUserId(map);
        } else if(user.getUserType() == 4 || user.getUserType() == 5 || user.getUserType() == 6){//分厂和巡检人员只能查看自己绑定的那个一个
            Map<String,Object> map = new HashMap<>();
            map.put("id",user.getShopId());
            shops = shopService.getPageByUserId(map);
        }
        model.addAttribute("shops", shops);
        model.addAttribute("shopPost", shopPost);
        return "module/shop/post/detail";
    }


    /**
     * 重置二维码
     */
    @Log("重置二维码")
    @PostMapping("/resetQrcode")
    @ResponseBody
    @RequiresPermissions("module:shoppost:edit")
    public R resetQrcode( Integer id) {
        ShopPost shopPost = shopPostService.findById(id);
        if(shopPost!=null){
            try{
                String qrcode = "";
                String fileName = "post_qr_"+shopPost.getShopId() + "_" + shopPost.getPostNum() +".jpg";
                String content = "{\"qrtype\":\"post\",\"shop_id\":"+shopPost.getShopId()+",\"num\":\""+shopPost.getPostNum()+"\"}";
                Aes aes = new Aes();
                content = aes.encrypt(content);
                System.out.println("content:  "+ content);
                //上传头像到OSS
                String img_key = "";
                int upload_type = OssUtil.TYPE_POST_PHOTOS;
                img_key = OssUtil.getUploadPrefix(upload_type) + fileName;
                QRCodeUtilEx.createQrCodeImg(content, shopPost.getPostNum() +"   NO. "+ shopPost.getPostNum(), null, uploadPath +"/"+ img_key, true);
                qrcode = img_key;
                shopPost.setQrCode(qrcode);
            }catch (Exception ex){
                ex.printStackTrace();
            }
            if (shopPostService.updateById(shopPost)) {
                return R.ok();
            }
        }
        return R.error();
    }


    @Log("编辑特殊岗位页面")
    @GetMapping("/edit/{id}")
    @RequiresPermissions("module:shoppost:edit")
    String edit(@PathVariable("id") Integer id, Model model) {
        UserDO user = getUser();
        ShopPost shopPost = shopPostService.getById(id);
        List<Shop> shops = new ArrayList<>();
        if(user.getUserType() == 0 || user.getUserType() == 1){//平台管理员可以查看所有的
            shops = shopService.selectAllList();
        } else if(user.getUserType() == 2 ){//集团管理员可以查看自己所管辖的
            Map<String,Object> map = new HashMap<>();
            map.put("jituan_user_id",user.getUserId());
            shops = shopService.getPageByUserId(map);
        } else if(user.getUserType() == 3){//片区管理员可以查看自己所管辖的
            Map<String,Object> map = new HashMap<>();
            map.put("sys_user_id",user.getUserId());
            shops = shopService.getPageByUserId(map);
        } else if(user.getUserType() == 4 || user.getUserType() == 5 || user.getUserType() == 6){//分厂和巡检人员只能查看自己绑定的那个一个
            Map<String,Object> map = new HashMap<>();
            map.put("id",user.getShopId());
            shops = shopService.getPageByUserId(map);
        }
        model.addAttribute("shops", shops);
        model.addAttribute("shopPost", shopPost);
        return "module/shop/post/detail";
    }


    @Log("编辑特殊岗位页面")
    @GetMapping("/record/check/{id}")
    @RequiresPermissions("module:shoppost:edit")
    String check(@PathVariable("id") Integer id, Model model) {
        UserDO user = getUser();
        ShopPostRecord record = shopPostRecordService.getById(id);
        model.addAttribute("record", record);
        return "module/shop/post/check";
    }

    /**
     * 修改
     */
    @Log("更新特殊岗位")
    @ResponseBody
    @RequestMapping("/checkOp")
    @RequiresPermissions("module:shoppost:edit")
    public R checkOp(@Valid ShopPostRecord record) {
        boolean bl = shopPostRecordService.updateById(record);
        if(bl){
            sendWxMsg(record);
            return R.ok();
        }
        return R.error();
    }


    /**
     *  岗位审批审核通过后，给申请人推送消息
     * @param record
     */
    private void sendWxMsg(ShopPostRecord record){
        try{
            WxUser user = wxUserService.findById(record.getUserId());
            if(user != null && StrUtil.isNotEmpty(user.getUnionId())){
                WxMsgTemplate template = getCheckRegTemplate(user,record);
                String param = JSONObject.fromObject(template).toString();
                String accessToken = WxMessage.getACCESSTOKEN(appidMp,secretMp);
                JSONObject jsonObject = WxMessage.sendMsg(accessToken,param);
                System.out.println("jsonObject:" + jsonObject.toString());
            }
        }catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
            System.out.println("发送失败" + e.getMessage());
        }
    }

    private WxMsgTemplate getCheckRegTemplate(WxUser user, ShopPostRecord record){
        UserDO sysUser = userService.findById(user.getSysUserId());
        WxMsgTemplate template = new WxMsgTemplate();
        WxTemplate wxTemplate = wxTemplateService.selectByUniqueColumn("template_type",5);
        UserMp userMp = userMpService.selectByUniqueColumn("unionid",user.getUnionId());
        if(userMp!=null){
            template.setTouser(userMp.getOpenid());
            template.setTemplate_id(wxTemplate.getTemplateId());
            template.setUrl("");
            Map<String, MsgTempData> m = new HashMap<>();

            MsgTempData first = new MsgTempData();
            first.setColor(wxTemplate.getFontColor());
            first.setValue(sysUser.getName() + "您好，您的岗位申请编号为"+record.getRegNo()+"的申请已批复");
            m.put("first",first);

            UserDO userDO = getUser();
            //审批人：
            MsgTempData keyword1 = new MsgTempData();
            keyword1.setColor(wxTemplate.getFontColor());
            keyword1.setValue(userDO.getName()+"("+userDO.getMobile()+")");
            m.put("keyword1",keyword1);

            //审批内容
            MsgTempData keyword2 = new MsgTempData();
            keyword2.setColor(wxTemplate.getFontColor());
            if(record.getCheckState() == 1){
                keyword2.setValue("审批已通过");
            }else if(record.getCheckState() == 2){
                keyword2.setValue("审批未通过");
            }
            m.put("keyword2",keyword2);

            //备注信息
            MsgTempData remark = new MsgTempData();
            remark.setColor(wxTemplate.getFontColor());
            remark.setValue("审批内容："+ record.getCheckResult());
            m.put("remark",remark);

            template.setData(m);
        }
        return template;
    }

    /**
     * 保存
     */
    @Log("新增OA审批")
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("module:shoppost:add")
    @Transactional
    public R save(@Valid ShopPost shopPost) {
        Shop shop = shopService.findById(shopPost.getShopId());
        if(shop!=null){
            shopPost.setShopName(shop.getShopName());
        }
        boolean ret = shopPostService.save(shopPost);
        if(ret){
            String pro_num = StringUtil.LeftBuCode(shopPost.getId().toString(),6);
            shopPost.setPostNum(pro_num);
            try{
                String qrcode = "";
                String fileName = "post_qr_"+shopPost.getShopId() + "_" + shopPost.getPostNum() +".jpg";
                String content = "{\"qrtype\":\"post\",\"shop_id\":"+shopPost.getShopId()+",\"num\":\""+shopPost.getPostNum()+"\"}";
                Aes aes = new Aes();
                content = aes.encrypt(content);
                System.out.println("content:  "+ content);
                //上传头像到OSS
                String img_key = "";
                int upload_type = OssUtil.TYPE_POST_PHOTOS;
                img_key = OssUtil.getUploadPrefix(upload_type) + fileName;
                QRCodeUtilEx.createQrCodeImg(content, shopPost.getPostNum() +"   NO. "+ shopPost.getPostNum(), null, uploadPath +"/"+ img_key, true);
                qrcode = img_key;
                shopPost.setQrCode(qrcode);
            }catch (Exception ex){
                ex.printStackTrace();
            }
            ret = shopPostService.updateById(shopPost);
            if(ret){
                return R.ok();
            }
        }
        return R.error();
    }


    @Log("导出列表")
    @GetMapping("/record/exportExcel")
    public void testExprotExcel(@RequestParam("begin_date") String begin_date, @RequestParam("end_date") String end_date,
                                @RequestParam("shopId") String shopId, HttpServletRequest request, HttpServletResponse response){
        UserDO user = getUser();
        Map<String,Object> map = new HashMap<>();
        if(user.getUserType() == 0 || user.getUserType() == 1){
            if(StrUtil.isNotEmpty(shopId)){
                map.put("shop_id",Integer.parseInt(shopId));
            }
        } else if(user.getUserType() == 2){//集团管理员
            if(StrUtil.isNotEmpty(shopId)){
                map.put("shop_id",Integer.parseInt(shopId));
            }else{
                map.put("jituan_user_id",user.getUserId());
            }
        }else if(user.getUserType() == 3){//片区管理员
            if(StrUtil.isNotEmpty(shopId)){
                map.put("shop_id",Integer.parseInt(shopId));
            }else{
                map.put("sys_user_id",user.getUserId());
            }
        }
        else if(user.getUserType() == 4 || user.getUserType() == 5 || user.getUserType() == 6){
            map.put("shop_id",user.getShopId());
        }

        if(StrUtil.isNotEmpty(begin_date) && StrUtil.isNotEmpty(end_date)){
            map.put("begin_time",begin_date +" 00:00:00");
            map.put("end_time",end_date +" 23:59:59");
        }
        List<ShopPostRecord> records = shopPostRecordService.selectByMap(map);
        records.forEach(record->{
            record.setCreateTimeStr(DateUtils.getTime(record.getCreateTime()));
        });
        ExcelUtils.writeExcel(response, records, ShopPostRecord.class, System.currentTimeMillis() + "_临时项目上报记录.xlsx");
    }


    /**
     * 修改
     */
    @Log("更新特殊岗位")
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("module:shoppost:edit")
    public R update(@Valid ShopPost shopPost) {

        if(StrUtil.isEmpty(shopPost.getShopName())){
            Shop shop = shopService.findById(shopPost.getShopId());
            if(shop!=null){
                shopPost.setShopName(shop.getShopName());
            }
        }
        if(StrUtil.isEmpty(shopPost.getPostNum())){
            String pro_num = StringUtil.LeftBuCode(shopPost.getId().toString(),6);
            shopPost.setPostNum(pro_num);
            try{
                String qrcode = "";
                String fileName = "post_qr_"+shopPost.getShopId() + "_" + shopPost.getPostNum() +".jpg";
                String content = "{\"qrtype\":\"post\",\"shop_id\":"+shopPost.getShopId()+",\"num\":\""+shopPost.getPostNum()+"\"}";
                Aes aes = new Aes();
                content = aes.encrypt(content);
                System.out.println("content:  "+ content);
                //上传头像到OSS
                String img_key = "";
                int upload_type = OssUtil.TYPE_POST_PHOTOS;
                img_key = OssUtil.getUploadPrefix(upload_type) + fileName;
                QRCodeUtilEx.createQrCodeImg(content, shopPost.getPostNum() +"   NO. "+ shopPost.getPostNum(), null, uploadPath +"/"+ img_key, true);
                qrcode = img_key;
                shopPost.setQrCode(qrcode);
            }catch (Exception ex){
                ex.printStackTrace();
            }
        }
        shopPostService.updateById(shopPost);
        return R.ok();
    }


    /**
     * 删除
     */
    @Log("删除临时项目")
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("module:shoppost:remove")
    @Transactional
    public R remove( Integer id) {
        try{
            if (shopPostService.removeById(id)) {
                return R.ok();
            }
        }catch (Exception e){

        }
        return R.error();
    }
}
